Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Java Arrays

  • In Java, an array is a collection of variables with similar types that go by one common name. Arrays function differently in Java than they do in C/C++.
    The following are a few key points regarding Java arrays.
    • All arrays are dynamically allocated in Java.
    • A contiguous memory location is used to store arrays.
    • A contiguous memory location is used to store arrays.
    • Java objects, such as arrays, have a property called length that can be used to determine their size. In C/C++, however, we use sizeof to determine length.
Table Of Content

  • Array in Java
  • Types of Array in java
  • Single Dimensional Array in java
  • Multidimensional Array in Java
  • Jagged Array in Java
  • Clone an array in Java
  • Arrays class in Java






  • Like other variables, a Java array variable can also be declared by adding [ ] after the data type.
  • The array's size cannot be changed (once initialized). An array reference can, however, be made to refer to another array.
  • This array storage enables us to access an array's elements at random.
  • The Java array also has other uses, such as static fields, local variables, and method parameters.
    An array's size must be specified as an int or short value, not a long one.
  • Each of the ordered variables in the array has an index starting at 0.
  • Object is the superclass of an array type.
    Every array type supports the Java.io.Serializable and Cloneable interfaces.






Types of Array in java

  • Single Dimensional Array
  • Multidimensional Array

Single Dimensional Array in java


Syntax to Declare an Array in Java
datatype [] array; // ex. int [] array;  
datatype array[]; // ex. int array[];   
datatype []array; // ex. int []array;   

Initialization of Java Array
public class Main {
	public static void main(String[] args) {
		int array[]= {10,20,30};   //arrays declared and Initialized
	}
}

Example of Single Dimensional Array in java




Example of Single Dimensional Array in java
 // Java example of Single Dimensional array 
public class Main {
	public static void main(String[] args) {
		int array[]= {10,20,30};   //arrays declare and Initialized
		for(int i=0;i<array.length;i++){
			System.out.println(array[i]); 
		}	
	}
}



Output:

10 
20 
30 

Array with for-each loop


Syntax of the for-each loop
for(datatype variable:array){  
    //body of the loop  
}  

Example:
for (int i : array) {
	//body of the loop  
}

Java example of Array with for-each loop
 // Java example of array with for-each loop 
public class Main {
	public static void main(String[] args) {
		int array[]= {10,20,30};   
		for (int arr : array) {
			System.out.println(arr); 
		}
	}
}



Output:

10 
20 
30 


For Each loop Next »



Index Out Of Bounds Exception in Java


When traversing an array with a length that is negative, equal to, or greater than the array size, the Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException.


Java example of ArrayIndexOutOfBoundsException
 // Java example of ArrayIndexOutOfBoundsException 
package HELLO;
public class Main {
	public static void main(String[] args) {
		int array[]= {10,20,30,40,50};   //arrays declare and Initialized
		for(int i=0;i<=5;i++){
			System.out.println(array[i]); 
		}
	}
}



Output:

10 
20 
30 
40 
50 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
	at HELLO/HELLO.Main.main(Main.java:8) 

How to Pass array to a Method in Java


Java example of Pass array to a Method in Java
 // Java example to find maximum of element of array 
public class Main {	
	static void Maximum(int arr[]) {
		int max=arr[0];  
		for(int i=1;i<arr.length;i++){  
		 if(max<arr[i])  
			 max=arr[i];     
		 } 
		 System.out.println(max); 
    }
	public static void main(String[] args){
		int array[]= {10,20,30,40,50};    
		Maximum(array);
	}
}



Output:

50 

How to returning array from the Method in Java


Java example of returning array from the Method in Java
 // Java example to returning Array from the Method 
public class Main {	
	public static int[] array(){  
		int[] array={10,20,30,40};   
		return array;  
	} 
	public static void main(String args[])  {  
		int[] array=array();           
		for (int i = 0; i < array.length; i++) {
			System.out.print(array[i]+ " "); 
		}			    
	}  
}



Output:

10 
20 
30 
40 


Anonymous Array in Java


Since Java supports anonymous arrays, you don't need to declare an array when passing it to a method.


Java example of anonymous array
 // Java example of anonymous array 
public class Main {	
	static void AnonymousArray(int array[]){  
	  for(int i=0;i<array.length;i++)  
	  System.out.println(array[i]);  
	}  	  
	public static void main(String args[]){  
		AnonymousArray(new int[]{10,20,30,40});//sending anonymous array to method  
	} 
}



Output:

10 
20 
30 
40 

Multidimensional Array in Java


Syntax to Declare an multidimensional Array in Java
datatype[][] array;  // e.g  int[][] array;  
datatype [][]array;  // e.g  int [][]array;  
datatype array[][];  // e.g  int array[][];    
datatype []array[];  // e.g  int []array[];

Initialization of Java Array
int[][] array=new int[2][3]; //2 row and 3 column  




Example of Multidimensional Array in java



Example of Multidimensional Array in java
 // Java example of Multidimensional arrays 
public class Main {	
	public static void main(String args[]){  
	  int[][] array={{10,20,30},{40,50,60},{70,80,90}};  
	  for(int i=0;i<array.length;i++){  
		  for(int j=0;j<array.length;j++){  
		    System.out.print(array[i][j]+" ");  
		  }  
		System.out.println();  
	 } 
   } 
}



Output:

10 20 30  
40 50 60  
70 80 90  

Jagged Array in Java


A jagged array is an array of arrays where each member array can be of a different size, allowing us to create a 2-D array with variable numbers of columns in each row. These arrays are also referred to as Jagged arrays.


Example of Jagged Array in Java
 // Java example of Jagged Array 
public class Main {	
	public static void main(String args[]){  
        // Declare a 2-D array with 3 rows
       int array[][] = new int[3][];
 
       //initialize and declare jagged array
 
       array[0] = new int[]{10,20,30};
       array[1] = new int[]{40,50,60,70};
       array[2] = new int[]{80,90,};
 
       // printing the jagged array
       System.out.println("Jagged Array:\n");
       for (int i=0; i<array.length; i++){
          for (int j=0; j<array[i].length; j++) {
        	  System.out.print(array[i][j] + " ");
           }
          System.out.println();
       }
   } 
}



Output:

Jagged Array: 
40 50 60 
40 50 60 70  
80 90 

How to Clone an array in Java


clone a single-dimensional array

We are able to clone the Java array because it implements the Cloneable interface. When a single-dimensional array is copied, a deep copy of the Java array is also created. This means that the actual value will be copied. However, when we copy a multidimensional array, it creates a shallow copy of the Java array, which means that the references are copied.


A "deep copy" is made when you clone a single-dimensional array, such as Object[], where the new array contains actual copies of the original array's elements rather than references.


Example of cloning of single-dimensional arrays in Java
 // Java example of cloning of single-dimensional arrays 
public class Main {	
	public static void main(String args[]){  
     int array[] = { 10, 20, 30 };    
     int clonedArr[] = array.clone();
     // will display false because a deep copy for a one-dimensional array is created.
     System.out.println(array == clonedArr);
     // print array
     for (int i = 0; i < clonedArr.length; i++) {
        System.out.print(clonedArr[i] + " ");
     }
   } 
}



Output:

false 
10 20 30 

Clone of a multi-dimensional array


A clone of a multi-dimensional array (such as Object[][]) is a "shallow copy," which means it creates only a single new array with each element array referencing an original element array, but subarrays are shared.


Example of cloning of multi-dimensional arrays in Java
 // Java example of cloning of multi-dimensional arrays 
public class Main {	
	public static void main(String args[]){  
        int array[][] = {{10,20,30}, {50,60}};     
        int cloneArr[][] = array.clone();
        System.out.println(array == cloneArr); //print false
        // will print true because shallow copy is used, which means that sub-arrays are shared
        System.out.println(array[0] == cloneArr[0]);
        System.out.println(array[1] == cloneArr[1]); 
   } 
}



Output:

false 
true 
true 

Arrays class in Java


The Arrays class in the java.util package is a Java Collection Framework component. This class provides static methods for creating and accessing Java arrays dynamically. It only has static methods and methods from the Object class. The methods of this class can be accessed via the class name.


Syntax: Declaration of class
public class Arrays extends Object

Syntax: Arrays
Arrays. <method name> ;


There are a number of static methods in the Arrays class in the java.util package that may be used to fill, sort, search, etc. in arrays. Let's now talk about the methods of this class


Example of sort of arrays in Java
 // Java example of sorting of arrays 
import java.util.Arrays;
public class Main {	
	public static void main(String args[]){  
        int array[] = {10, 20, 05, 02, 30};        
        Arrays.sort(array); // array sort        
        System.out.println("Sorted Array is : "+ Arrays.toString(array));
   } 
}



Output:

Sorted Array is : [2, 5, 10, 20, 30] 
Java String Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Array
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.